<template>
  <div class="space-user-analyze">
    <a-card title="空间用户上传行为分析" style="width: 100%">
      <v-chart :option="options" style="height: 320px; max-width: 100%;" :loading="loading" />
        <template #extra>
          <a-space>
            <a-segmented v-model:value="timeDimension" :options="timeDimensionOptions" />
            <a-input-search allowClear placeholder="请输入用户 id" enter-button @search="doSearch" />
          </a-space>
        </template>
    </a-card>
  </div>
</template>

<script setup lang="ts">

// 定义父组件传递的参数
import { computed, ref, watchEffect } from 'vue'
import { getSpaceUserAnalyzeUsingPost } from '@/api/spaceAnalyzeController'
import { message } from 'ant-design-vue'
import VChart from "vue-echarts";
import "echarts";

interface props {
  queryAll?: boolean
  queryPublic?: boolean
  spaceId?: number
}

// 使用withDefaults定义默认值
const props = withDefaults(defineProps<props>(), {
  queryAll: false,
  queryPublic: false
})

// 定义加载状态
const loading = ref(true)

// 定义获取的数据源
const dataList = ref<API.SpaceUserAnalyzeVO[]>([])

// 定义用户 id
const userId = ref<string>()
// 定义时间维度
const timeDimension = ref<string>('day')
// 定义时间维度的默认选项
const timeDimensionOptions = [
  {
    label: '日',
    value: 'day',
  },
  {
    label: '周',
    value: 'week',
  },
  {
    label: '月',
    value: 'month',
  },
]

/**
 * 根据用户 id 搜索用户 (在触发搜索时才要改变用户 id ，防止抖动)
 * @param value
 */
const doSearch = (value: string) => {
  userId.value = value
}

// 向后端获取空间资源的使用情况
const getSpaceUserAnalyze = async () => {
  loading.value = true

  const res = await getSpaceUserAnalyzeUsingPost({
    queryAll: props.queryAll,
    queryPublic: props.queryPublic,
    spaceId: props.spaceId,
    // @ts-ignore
    userId: userId.value,
    timeDimension: timeDimension.value
  })
  if (res.data.code === 0 && res.data.data) {
    dataList.value = res.data.data ?? []
  } else {
    message.error('获取数据失败，' + res.data?.message)
  }

  loading.value = false
}

// 监听变量的变化，变量变化时重新加载数据
watchEffect(() => {
  getSpaceUserAnalyze()
})


/* 定义 echarts 的 option */
// 用 computed 计算属性定义，使变量发生变化时，echarts 也会重新渲染
const options = computed(() => {
  const periods = dataList.value.map((item) => item.period) // 时间区间
  const counts = dataList.value.map((item) => item.count) // 上传数量

  return {
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: periods, name: '时间区间' },
    yAxis: { type: 'value', name: '上传数量' },
    series: [
      {
        name: '上传数量',
        type: 'line',
        data: counts,
        smooth: true, // 平滑折线
        emphasis: {
          focus: 'series',
        },
      },
    ],
  }
})



</script>

<style scoped>

</style>
